package initialize

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"go.uber.org/zap"
	"process/global"
	"time"
)

var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	fmt.Println("Connected")
	global.GVA_LOG.Info("MQTT connected successfully.")
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	fmt.Printf("Connect lost: %v", err)
	global.GVA_LOG.Error("MQTT connection lost:", zap.Error(err))
	reconnect(client)
}

func reconnect(client mqtt.Client) {
	for {
		time.Sleep(5 * time.Second) // Wait before retrying to connect
		if token := client.Connect(); token.Wait() && token.Error() != nil {
			global.GVA_LOG.Error("Failed to reconnect MQTT:", zap.Error(token.Error()))
		} else {
			global.GVA_LOG.Info("Reconnected to MQTT successfully.")
			break
		}
	}
}

func Mqtt() {
	mqttCfg := global.GVA_CONFIG.Mqtt
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", mqttCfg.Broker, mqttCfg.Port))
	opts.SetClientID(mqttCfg.ClientID)
	opts.SetUsername(mqttCfg.Username)
	opts.SetPassword(mqttCfg.Password)
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	opts.SetKeepAlive(60 * time.Second) // Set keep alive interval to 60 seconds
	opts.SetPingTimeout(20 * time.Second) // Set ping timeout to 20 seconds
	opts.SetAutoReconnect(true) // Enable auto-reconnect

	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		global.GVA_LOG.Error("MQTT connect failed:", zap.Error(token.Error()))
	} else {
		global.GVA_LOG.Info("MQTT connect success:")
		global.GVA_MQTT = client
	}
}